package live.zs.codec;

import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import live.zs.Fruit;
import org.bson.*;
import org.bson.codecs.Codec;
import org.bson.codecs.CollectibleCodec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;

import java.util.UUID;

/**
 * @author madison
 * @description
 * @date 2022/2/7 14:16
 */
public class FruitCodec implements CollectibleCodec<Fruit> {
    private final Codec<Document> documentCodec;

    public FruitCodec() {
        this.documentCodec = MongoClientSettings.getDefaultCodecRegistry().get(Document.class);
    }

    @Override
    public Fruit generateIdIfAbsentFromDocument(Fruit fruit) {
        if (!documentHasId(fruit)) {
            fruit.setId(UUID.randomUUID().toString());
        }
        return fruit;
    }

    @Override
    public boolean documentHasId(Fruit fruit) {
        return fruit.getId() != null;
    }

    @Override
    public BsonValue getDocumentId(Fruit fruit) {
        return new BsonString(fruit.getId());
    }

    @Override
    public Fruit decode(BsonReader bsonReader, DecoderContext decoderContext) {
        return null;
    }

    @Override
    public void encode(BsonWriter writer, Fruit fruit, EncoderContext encoderContext) {
        Document doc = new Document();
        doc.put("name", fruit.getName());
        doc.put("description", fruit.getDescription());
        documentCodec.encode(writer, doc, encoderContext);
    }

    @Override
    public Class<Fruit> getEncoderClass() {
        return Fruit.class;
    }
}
